/*---------------------------------------------------------------------
Project:
Purpose:	Content Provider (SQLite)
Author:		Ho-Jung Kim (godmode2k@hotmail.com | MSN)
Date:		April 27, 2011
File:		CContentProvider.java
License:	n/a
Last Modified Date: April 29, 2011
-----------------------------------------------------------------------
NOTE:
			* Source: Using and Implementing Content Providers in Android
			 - http://www.devx.com/wireless/Article/41133/

 			* AndroidManifest.xml
 				...
				<application ...>
					...
					<provider android:name="CContentProvider"
						android:authorities="com.android.myTest1" />
				</application>
				
			* USAGE
			{ // example from source reference
				//---add a book---
				ContentValues values = new ContentValues();
				values.put( BooksProvider.TITLE, "C# 2008 Programmer's Reference" );
				values.put( BooksProvider.ISBN, "0470285818" );
				Uri uri = getContentResolver().insert( BooksProvider.CONTENT_URI, values );

				//---add another book---
				values.clear();
				values.put( BooksProvider.TITLE, "Programming Sudoku" );
				values.put( BooksProvider.ISBN, "1590596625" );
				uri = getContentResolver().insert( BooksProvider.CONTENT_URI, values );
				
				ContentValues values = new ContentValues();
				values.put( "title", "ASP.NET 2.0: A Developer's Notebook" );
				values.put( "isbn", "0596008120" );
				Uri uri = getContentResolver().insert(
					Uri.parse("content://com.android.myTest1/books"), values );

				Uri allTitles = Uri.parse( "content://com.android.myTest1/books" );
				Cursor c = managedQuery( allTitles, null, null, null, "title desc" );
				if( c.moveToFirst() ) {
					do {
						Toast.makeText(this,
							c.getString(c.getColumnIndex(
							BooksProvider._ID)) + ", " +
							c.getString(c.getColumnIndex(
							BooksProvider.TITLE)) + ", " +
							c.getString(c.getColumnIndex(
							BooksProvider.ISBN)),
						Toast.LENGTH_LONG).show();

						String strId = c.getString( c.getColumnIndex(BooksProvider._ID) );
						String strTitle = c.getString( c.getColumnIndex(BooksProvider.TITLE) );
						String strIsbn = c.getString( c.getColumnIndex(BooksProvider.ISBN) );
						Log.d( TAG, "id = " + strId + ", title = " + strTitle + ", isbn = " + strIsbn );
					} while( c.moveToNext() );
				}
				
				ContentValues editedValues = new ContentValues();
				editedValues.put( BooksProvider.TITLE, "Programming Sudoku (Apress)" );
				getContentResolver().update(
					Uri.parse(
						"content://com.android.myTest1/books/2"),
						editedValues,
						null,
						null);

				getContentResolver().delete(
					Uri.parse("content://com.android.myTest1/books/2"), null, null );

				getContentResolver().delete(
					Uri.parse("content://com.android.myTest1/books"), null, null );
			} // end of example from source reference
					

			// -----------------------------------------------------------

			{ // CContentProvider Example
 
				//
				// CContentProvider Example
				//

				#DB: DB_CPtest
				#TABLE NAME: info
				#TABLE DESCRIPTION:
					_id | title | data | data2 (extra)

				// Get all of data
				Uri allTitles = Uri.parse( "content://com.android.myTest1/db_cptest" );
				Cursor c = managedQuery( allTitles, null, null, null, "_id asc" );
				if( c.moveToFirst() ) {
					do {
						//Toast.makeText(this,
						//	c.getString(c.getColumnIndex(CContentProvider._ID)) + ", " +
						//	c.getString(c.getColumnIndex(CContentProvider.TITLE)) + ", " +
						//	c.getString(c.getColumnIndex(CContentProvider.DATA)) + ", " +
						//	c.getString(c.getColumnIndex(CContentProvider.DATA2)),
						//Toast.LENGTH_LONG).show();

						String strId = c.getString( c.getColumnIndex(CContentProvider._ID) );
						String strTitle = c.getString( c.getColumnIndex(CContentProvider.TITLE) );
						String strData = c.getString( c.getColumnIndex(CContentProvider.DATA) );
						String strData2 = c.getString( c.getColumnIndex(CContentProvider.DATA2) );
						Log.d( TAG, "id = " + strId + ", title = " + strTitle + ", data = " + strData + ", data2 = " + strData2 );
					} while( c.moveToNext() );
				}

				// INSERT
				ContentValues values = new ContentValues();
				values.put( "title", "title1" );
				values.put( "data", "data" );
				values.put( "data2", "extra" );
				Uri uri = Uri.parse( "content://com.android.myTest1/db_cptest" );
				Uri resUri = getContentResolver().insert( uri, values );
				
				// UPDATE #1
				ContentValues values = new ContentValues();
				values.put( "data", "data" );
				Uri uri = Uri.parse( "content://com.android.myTest1/db_cptest/1" );
				int resRowCount = getContentResolver().update( uri, values, null, null );
				if( resRowCount > 0 )
					Log.d( TAG, "Updated [TRUE]" );
				else
					Log.d( TAG, "Updated [FALSE]" );

				// UPDATE #2
				ContentValues values = new ContentValues();
				values.put( "data", "data" );
				Uri uri = Uri.parse( "content://com.android.myTest1/db_cptest" );
				String[] strParam = { "title1" };
				int resRowCount = getContentResolver().update( uri, values, "title=?", strParam );
				if( resRowCount > 0 )
					Log.d( TAG, "Updated [TRUE]" );
				else
					Log.d( TAG, "Updated [FALSE]" );
			} // end of CContentProvider Example
-----------------------------------------------------------------------*/

package com.android.myTest1;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

public class CContentProvider extends ContentProvider {
   public static final String PROVIDER_NAME = "com.android.myTest1";
   
   public static final Uri CONTENT_URI = Uri.parse( "content://" + PROVIDER_NAME + "/db_cptest" );
   
   public static final String _ID = "_id";
   public static final String TITLE = "title";
   public static final String DATA = "data";
   public static final String DATA2 = "data2";
   
   private static final int INFO = 1;
   private static final int INFO_ID = 2;

   private static final UriMatcher uriMatcher;
   static{
      uriMatcher = new UriMatcher( UriMatcher.NO_MATCH );
      uriMatcher.addURI( PROVIDER_NAME, "db_cptest", INFO );
      uriMatcher.addURI( PROVIDER_NAME, "db_cptest/#", INFO_ID );
   }   
   
   //---for database use---
   private SQLiteDatabase dbInfo;
   private static final String DATABASE_NAME = "DB_CPtest";
   private static final String DATABASE_TABLE = "info";
   private static final int DATABASE_VERSION = 1;
   private static final String DATABASE_CREATE =
         "create table " + DATABASE_TABLE + 
         " (_id integer primary key autoincrement, "
         + "title text not null, data text not null, data2 text not null);";
   
   private static class DatabaseHelper extends SQLiteOpenHelper {
      DatabaseHelper(Context context) {
         super( context, DATABASE_NAME, null, DATABASE_VERSION );
      }

      @Override
      public void onCreate(SQLiteDatabase db) {
         db.execSQL( DATABASE_CREATE );
      }

      @Override
      public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
         Log.w( "Content provider database", 
              "Upgrading database from version " + 
              oldVersion + " to " + newVersion + 
              ", which will destroy all old data" );
         db.execSQL( "DROP TABLE IF EXISTS titles" );
         onCreate( db );
      }
   }   
   //...
   //...

   @Override
   public boolean onCreate() {
      Context context = getContext();
      DatabaseHelper dbHelper = new DatabaseHelper( context );
      dbInfo = dbHelper.getWritableDatabase();
      return (dbInfo == null)? false : true;
   }

   @Override
   public String getType(Uri uri) {
      switch( uriMatcher.match(uri) ) {
         //---get all books---
         case INFO:
            return "vnd.android.cursor.dir/vnd.com.android.myTest1 ";
         //---get a particular book---
         case INFO_ID:                
            return "vnd.android.cursor.item/vnd.com.android.myTest1 ";
         default:
            throw new IllegalArgumentException( "Unsupported URI: " + uri );        
      }   
   }

   @Override
   public Cursor query(Uri uri, String[] projection, String selection,
      String[] selectionArgs, String sortOrder) {
           
      SQLiteQueryBuilder sqlBuilder = new SQLiteQueryBuilder();
      sqlBuilder.setTables( DATABASE_TABLE );
       
      if( uriMatcher.match(uri) == INFO_ID )
         //---if getting a particular book---
         sqlBuilder.appendWhere( _ID + " = " + uri.getPathSegments().get(1) );                
       
      if( sortOrder == null || sortOrder == "" )
         sortOrder = TITLE;
   
      Cursor c = sqlBuilder.query(
         dbInfo, 
         projection, 
         selection, 
         selectionArgs, 
         null, 
         null, 
         sortOrder);
   
      //---register to watch a content URI for changes---
      c.setNotificationUri( getContext().getContentResolver(), uri );
      return c;
   }
   
   @Override
   public Uri insert(Uri uri, ContentValues values) {
      //---add a new book---
      long rowID = dbInfo.insert( DATABASE_TABLE, "", values );

      //---if added successfully---
      if( rowID > 0 ) {
         Uri _uri = ContentUris.withAppendedId( CONTENT_URI, rowID );
         getContext().getContentResolver().notifyChange( _uri, null );
         return _uri;
      }

      throw new SQLException( "Failed to insert row into " + uri );
   }
   
   @Override
   public int delete(Uri arg0, String arg1, String[] arg2) {
      // arg0 = uri
      // arg1 = selection
      // arg2 = selectionArgs
      int count=0;
      switch( uriMatcher.match(arg0) ) {
         case INFO:
            count = dbInfo.delete( DATABASE_TABLE, arg1, arg2 );
            break;
         case INFO_ID:
            String id = arg0.getPathSegments().get(1);
            count = dbInfo.delete(
               DATABASE_TABLE,
               _ID + " = " + id + 
               (!TextUtils.isEmpty(arg1) ? " AND (" + 
               arg1 + ')' : ""), 
               arg2);
            break;

         default: throw new IllegalArgumentException( "Unknown URI " + arg0 );
      }

      getContext().getContentResolver().notifyChange( arg0, null );
      return count;
   }
   
   @Override
   public int update(Uri uri, ContentValues values, 
      String selection, String[] selectionArgs) {
      int count = 0;
      switch( uriMatcher.match(uri) ) {
         case INFO:
            count = dbInfo.update(
               DATABASE_TABLE, 
               values,
               selection, 
               selectionArgs);
            break;
         case INFO_ID:                
            count = dbInfo.update(
               DATABASE_TABLE, 
               values,
               _ID + " = " + uri.getPathSegments().get(1) + 
               (!TextUtils.isEmpty(selection) ? " AND (" + 
                  selection + ')' : ""), 
                selectionArgs);
            break;

         default: throw new IllegalArgumentException( "Unknown URI " + uri );
      }

      getContext().getContentResolver().notifyChange( uri, null );
      return count;
   }
}